<template>
	<uni-nav-bar title="充值" left-icon="left" @clickLeft="navBack()" :fixed="true" statusBar></uni-nav-bar>
	<environment></environment>
	<view class="flex-col-hcenter">
		<!-- top box -->
		<view class="flex-col-hcenter top-box" @click="navTo('account/account')">
			<view style="font-size: 32rpx; margin-top: 64rpx">总资产</view>
			<view class="flex" style="margin-top: 22rpx">
				<view style="font-size: 26rpx; margin-top: 24rpx">¥</view>
				<view style="font-size: 50rpx">{{ balance ? balance : '0.00' }}</view>
			</view>
		</view>
		<!-- ad images -->
		<swiper class="ad-img-swiper" circular :autoplay="true" :interval="3000" :duration="1000">
			<swiper-item v-for="(item, index) in adImgList" :key="index">
				<image class="ad-img-swiper" :src="item.imageurl"></image>
			</swiper-item>
		</swiper>
		<!-- fast recharging box -->
		<view class="flex-col-hcenter card-box">
			<view class="lbl-bar flex-vcenter flex-jcsb">
				<view style="color: #333">
					<text>充值金额</text>
					<text style="color: #666;font-size: 24rpx;margin-left: 5rpx;">单位(元)</text>
				</view>
				<view style="color: #666;" @click="navTo('giftCard/tokenCard')">
					绑卡
					<uni-icons type="forward" size="20" color="#666"
						:style="{ marginBottom: isH5 ? '' : '-2rpx' }"></uni-icons>
				</view>
			</view>
			<view class="btns-box">
				<view v-for="(item, index) in btnArr" :key="index" class="flex-center btn-item"
					:class="{ picked: item === amount }" @click="setAmount(item)">
					{{ item }}
				</view>
				<view class="flex-center btn-item" @click="openAmountPad">输入金额</view>
			</view>
		</view>
		<view class="package space-between" v-if="GemNum">
			<view style="color:#1b91ff;font-size:40rpx;"><text style="font-size:28rpx;">￥</text>{{amount}}</view>
			<view style="font-size:28rpx;">获赠蓝宝石:{{GemNum}}颗</view>
		</view>
		<!-- <view class="illustrate" v-if="GemNum" @click="navTo('gemstone/recharge')">{{contents}}>></view> -->
		<!-- pay btn -->
		<view class="flex-center pay-btn" @click="fastToPay('2')">
			<view>
				充值
				<text style="font-size: 48rpx; padding: 0 16rpx">{{ amount }}</text>
				元
			</view>
		</view>
		<!-- tip box -->
		<view class="flex tip-box">
			<view>点击充值表示已经确认阅读并同意</view>
			<view class="rule-btn" @click="navTo('account/terms')">充值规则</view>
		</view>
		<view class="flex-center lookFor" @click="fastToPay('1')">找人充</view>
	</view>
	<!-- amount popup -->
	<uni-popup ref="popup" type="bottom" style="z-index: 910" :safe-area="isH5" @change="onAmountPadChange">
		<AmountPad v-if="isShowAmountPad" @toPay="closeAmountPad" />
	</uni-popup>
	<!-- 同意协议 -->
	<uni-popup ref="agreementPopup" type="center" style="z-index: 910">
		<Agreement @confirm="continueToPay" />
	</uni-popup>
	<!-- 不能支付 -->
	<uni-popup ref="proupPay" type="center">
		<view class="popup" @click="telCall('400-109-1606')">
			<text>充值</text>
			<text>{{text}}</text>
		</view>
	</uni-popup>
	<!-- 扫码加注支付 -->
	<CodeFilliBot :num="FillingMoney" :union_id="FillingUnion_id" :state="FillingState" :from_id="driver_id"
		ref="disbursement" :type="FillingType" :teamId="FillingTeamId">
	</CodeFilliBot>
	<!-- 验证手机号码 -->
	<TestVerify ref="phone" @confirm="confirm" :gemBei="gemBei"></TestVerify>
	<!-- 去福利商城兑换商品弹框 -->
	<ConvertPop ref="convert"></ConvertPop>
	<!-- 升级包弹框 -->
	<UpgradePop ref="upgrade" @expansion="expansion"></UpgradePop>
	<webWechat></webWechat>
</template>

<script setup lang="ts">
	import { telCall } from '@/utils/copyText';
	import CodeFilliBot from '@c/canCode/CodeFilliBot.vue';
	import TestVerify from '@c/mine/testVerify.vue';
	import UpgradePop from '@c/mine/upgradePop.vue';
	import ConvertPop from '@c/mine/convertPop.vue';
	import { balanceInfo, indexInfo } from '@/gql/account';
	import { getGem } from '@/gql/gemstone';
	import { BalanceInfoQuery, IndexInfoQuery } from '@/gql/types/gql';
	import { navBack, navTo, redirectTo } from '@/utils/navigator';
	import { isH5 } from '@/utils/platform';
	import { errorToast, showLoading, showToast, successToast } from '@/utils/prompt';
	import { authorMe } from '@/gql/user';
	import Agreement from '@c/prepayment/Agreement.vue';
	import AmountPad from '@c/prepayment/AmountPad.vue';
	import environment from '@c/pobulic/environment.vue';
	import webWechat from '@c/pobulic/webWechat.vue';
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import { getDriverID } from '@/stores/driverID';
	import { toPublish } from '@mqtt';
	import type { Ref } from 'vue';
	import { ref } from 'vue';
	import { useUserStore } from '@/stores/user';
	/**
	 *
	 * 充值主页
	 * @param userInfo  用户信息
	 * @param btnArr  充值金额列表
	 * @param adImgList  轮播图列表
	 * @param driver_id  用户ID
	 * @param amount  当前充值金额
	 * @param paymentAmount  存储当前充值金额
	 * @param isShowAmountPad  存储当前充值金额
	 * @param popup  充值金额弹框值
	 * @param agreementPopup  协议弹框
	 * @param types  返回状态判别
	 * @return {type}
	 */
	const userInfo = useUserStore();
	// static
	const btnArr : Ref<string[]> = ref([]);
	const adImgList = ref([]);
	const balance = ref('');
	const driver_id = getDriverID();
	// data
	const amount = ref();
	let paymentAmount = 0;
	const isShowAmountPad = ref(false);
	// refs
	const popup = ref(null);
	const agreementPopup = ref(null);
	const types = ref()
	const proupPay = ref(null)
	const text = ref('')
	const GemNum = ref()
	const isCheck = ref(0)
	const contents = ref()

	const disbursement = ref(null)
	const phone = ref(null)
	const convert = ref(null)
	const upgrade = ref(null)
	const gemBei = ref()


	const pattern = ref('2')//支付方式 1找人代充 2自己充值
	const repeat = ref(true)//放重复点击
	//扫码加注信息
	const FillingAmount = ref() //加注量
	const FillingPrice = ref() //加注单价
	const FillingMoney = ref() //加注单价
	const FillingTeamId = ref() //团ID
	const FillingState = ref() //用户身份
	const FillingType = ref() //用户状态
	const FillingUnion_id = ref() //用户状态
	onLoad((pearm) => {
		FillingAmount.value = pearm.amount
		FillingPrice.value = pearm.price
		FillingMoney.value = pearm.money
		FillingTeamId.value = pearm.teamId
		FillingState.value = pearm.state
		FillingType.value = pearm.type
		FillingUnion_id.value = pearm.union_id
		amount.value = pearm.money
	})
	// get data
	/**
	 * 金额列表
	 */
	function initHandler(obj : { data : IndexInfoQuery }) {
		const { data } = obj;
		adImgList.value = [data.ads[0]];
		btnArr.value = data.get_myblock.content.split(',');
		amount.value = amount.value ? amount.value : btnArr.value[0];
		getGems(amount.value)
	}
	/**
	 * 获取金额列表
	 */
	function init() {
		showLoading('加载中');
		const payload = {
			query: indexInfo,
			variables: {
				infoType: 'zdy_money',
				adType: 'driver_recharge',
				driver_id,
			},
		};
		toPublish('ql/driver/index', payload, initHandler);
	}
	/**
	 * 获取当前用户总资产
	 */
	function getBalance() {
		const payload = {
			query: balanceInfo,
			variables: { driver_id: uni.getStorageSync('storage_key').id },
		};
		toPublish('ql/driver/balanceInfo', payload, (obj : { data : BalanceInfoQuery }) => {
			const { data } = obj;
			balance.value = data.driver_info.money.toString();
		});
	}

	init();
	onShow(getBalance);

	// setAmount
	/**
	 * 存储选中的充值金额
	 */
	function setAmount(value : string) {
		amount.value = value;
		getGems(amount.value)
	}

	// AmountPad
	/**
	 * 打开手动输入金额弹框
	 */
	function openAmountPad() {
		isShowAmountPad.value = true;
		popup.value.open();
	}
	/**
	 * 关闭手动输入金额弹框
	 */
	function closeAmountPad(money : number) {
		isShowAmountPad.value = false;
		popup.value.close();
		amount.value = money
		getGems(amount.value)
	}
	/**
	 * 操作手动输入金额弹框
	 */
	function onAmountPadChange({ show } : { show : boolean }) {
		if (!show) {
			isShowAmountPad.value = false;
		}
	}

	// pay
	/**
	 * 点击底部充值按钮
	 */
	function fastToPay(num : string) {
		pattern.value = num
		const pubMsg = {
			driver_id: driver_id,
		};
		toPublish('driver/getIsRecharge', pubMsg, (obj : any) => {
			const { code, msg } = obj;
			text.value = msg
			if (code === 1) {
				const val = Number.parseInt(amount.value);
				toPay(val);
			} else {
				proupPay.value.open()
			}
		});
	}
	/**
	 * 确认充值
	 */
	function toPay(amount : number) {
		const isAgreed = uni.getStorageSync('agreens') === new Date().getDate();
		if (isAgreed) {
			showLoading('请求订单');
			const payload = {
				driver_id,
				order_type: 'recharge',
				method: isH5 ? 'mp' : 'mini',
				amount,
			};
			if (!repeat.value) {
				return
			}
			repeat.value = false
			toPublish('order_recharge/addOrder', payload, orderHandler, () => errorToast('请求订单超时'));
		} else {
			paymentAmount = amount;
			agreementPopup.value.open();
		}
	}
	/**
	 * 同意充值协议
	 */
	function continueToPay() {
		agreementPopup.value.close();
		// toPay(paymentAmount);
	}
	/**
	 * 提交金额支付订单的反馈
	 */
	function orderHandler(obj : any) {
		if (obj.code === 1 && pattern.value === '2') {
			launchPayment(obj.data);
		} else if (obj.code === 1 && pattern.value === '1') {
			repeat.value = true
			navTo('account/payFor?id=' + obj.data.order_id)
		} else {
			repeat.value = true
			errorToast(obj.msg);
		}
	}
	/**
	 * 微信支付
	 */
	function launchPayment({ order_id, msg_id }) {
		showLoading('发起支付');
		const payload = {
			order_type: 'recharge',
			order_id,
			type: 'wechat',
			method: isH5 ? 'mp' : 'mini',
			msg_id,
		};
		toPublish('order_recharge/payOrder', payload, paymentHandler, () => errorToast('发起支付超时'));
	}
	/**
	 * 微信支付
	 */
	function paymentHandler(obj : any) {
		if (obj.code === 1) {
			repeat.value = true
			// @ts-ignore
			WeixinJSBridge.invoke('getBrandWCPayRequest', obj.data, function (res : any) {
				switch (res.err_msg) {
					case 'get_brand_wcpay_request:ok':
						onSuccess();
						break;
					case 'get_brand_wcpay_request:cancel':
						showToast('充值取消');
						break;
					case 'get_brand_wcpay_request:fail':
						errorToast('充值失败');
						break;
				}
				// if (res.err_msg == 'get_brand_wcpay_request:ok') {
				//   // 使用以上方式判断前端返回,微信团队郑重提示：
				//   //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
				// }
			});
		} else {
			repeat.value = true
			errorToast(obj.msg);
		}
	}
	/**
	 * 微信支付成功回调
	 */
	function onSuccess() {
		if (isShowAmountPad.value) {
			closeAmountPad();
		}
		getBalance();
		userInfo.gemstone()
		successToast('充值成功');
		userInfo.getUserInfo();
		setTimeout(() => {
			upgrade.value.init()
			if (FillingAmount.value) {
				if (userInfo.money < FillingMoney.value) {
					errorToast('当前余额不足');
					return
				} else {
					disbursement.value.submit('money', FillingAmount.value, FillingPrice.value)
					return
				}
			} else {
				amount.value = btnArr.value[0];
				// navBack()
			}
		}, 1000)
	}
	// else if (FillingType.value == 1) {
	// 	navBack()
	// 	return
	// } 
	/**
	 * 获取蓝宝石信息
	 */
	function getGems(num : number) {
		const payload = {
			query: getGem,
			variables: {
				driver_id,
				money: Number(num)
			},
		};
		toPublish('ql/score/getGem', payload, (obj : any) => {
			uni.hideLoading();
			const { getGem } = obj.data;
			GemNum.value = getGem.gem;
			isCheck.value = getGem.is_check
			gemBei.value = getGem.gem_bei
		});
	}
	content()
	function content() {
		const payload = {
			query: authorMe,
			variables: { code: 'lbsts' },
		};
		toPublish('ql/driver/getMyblock', payload, (obj : any) => {
			const { data } = obj;
			contents.value = data.get_myblock.content;
		});
	}
	function expansion() {
		phone.value.open()
	}
	function confirm() {
		convert.value.open()
	}
</script>

<style scoped lang="less">
	.illustrate {
		width: 96%;
		margin: 0rpx auto;
		color: #666;
		font-size: 26rpx;
		line-height: 40rpx;
		text-align: right;
	}

	.top-box {
		background-image: url(https://admin.anlan.tech/uploads/20221023/aa78cfcec92006930c355b1305a5dbaf.png);
		background-repeat: no-repeat;
		background-size: contain;
		width: 722rpx;
		height: 282rpx;
		margin-top: 10rpx;
		color: white;
		letter-spacing: 2rpx;
	}

	.ad-img-swiper {
		width: 722rpx;
		height: 204rpx;
	}

	.card-box {
		margin-top: 16rpx;
		width: 720rpx;
		background: white;
		box-shadow: 2rpx 4rpx 8rpx 0 rgba(204, 204, 204, 0.5);
		border-radius: 5px;

		.lbl-bar {
			width: 690rpx;
			height: 40rpx;
			padding: 0 30rpx;
			margin: 30rpx 0;
			font-size: 28rpx;
			letter-spacing: 2rpx;

			view {
				display: flex;
				align-items: flex-end;
			}
		}
	}

	.btns-box {
		padding-bottom: 44rpx;
		display: grid;
		grid-template-columns: repeat(3, 218rpx);
		gap: 15rpx 15rpx;
		font-size: 36rpx;
		letter-spacing: 3rpx;
		color: #1b91ff;

		.btn-item {
			height: 112rpx;
			background-color: white;
			border-radius: 5px;
			border: 2rpx solid #1b91ff;
			box-shadow: 2rpx 4rpx 8rpx 0 rgba(204, 204, 204, 0.5);

			&.picked {
				color: white;
				background: #1b91ff;
			}
		}
	}

	.pay-btn {
		margin-top: 40rpx;
		width: 720rpx;
		height: 80rpx;
		background: linear-gradient(69deg, #41a3ff 0%, #1b91ff 100%);
		border-radius: 5px;
		font-size: 36rpx;
		color: white;
		letter-spacing: 4rpx;
	}

	.lookFor {
		margin: 20rpx auto;
		width: 720rpx;
		height: 80rpx;
		border: 1px solid #1b91ff;
		border-radius: 5px;
		font-size: 36rpx;
		color: #1b91ff;
	}

	.tip-box {
		margin: 40rpx 0;
		font-size: 24rpx;
		letter-spacing: 2rpx;
		color: #666;
	}

	.rule-btn {
		color: #1b91ff;

		&::before {
			content: '<';
		}

		&::after {
			content: '>';
		}
	}

	.popup {
		width: 600rpx;
		margin: 0px auto;
		background-color: white;
		border-radius: 5px;
		padding: 30rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;

		text:nth-of-type(1) {
			margin-bottom: 20rpx;
		}
	}
</style>